package com.github.yeecode.mybatisdemo.reflect;

import com.github.yeecode.mybatisdemo.model.User;
import org.apache.ibatis.reflection.Reflector;
import org.apache.ibatis.reflection.ReflectorFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author : wushikai
 * <p>
 * date : 2021-01-16
 *
 * DefaultReflectorFactory直接使用HashMap缓存Reflector，key是Class，value是Reflector。
 */
public class MyDefaultReflectorFactory  implements ReflectorFactory {

    private boolean classCacheEnabled = true;
    private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<>();

    public MyDefaultReflectorFactory() {
    }

    @Override
    public boolean isClassCacheEnabled() {
        return classCacheEnabled;
    }

    @Override
    public void setClassCacheEnabled(boolean classCacheEnabled) {
        this.classCacheEnabled = classCacheEnabled;
    }

    @Override
    public Reflector findForClass(Class<?> type) {
        if (classCacheEnabled) {
            // synchronized (type) removed see issue #461
            return reflectorMap.computeIfAbsent(type, Reflector::new);  //Reflector::new Java 8的新写法
        } else {
            return new Reflector(type);
        }
    }
    public static void main(String[] args){
        //User user = User::toString; 不能那么写, :: 必须放在函数式接口之中;
    }
}
